using System;
using System.Windows;
using System.Windows.Controls;

namespace GraphMyCode.Client.Controls
{
	public class ZoomBox : Control
	{
		public static readonly DependencyProperty MaxValueProperty =
			DependencyProperty.Register("MaxValue", typeof (double), typeof (ZoomBox), new PropertyMetadata(3.0));

		public static readonly DependencyProperty MinValueProperty =
			DependencyProperty.Register("MinValue", typeof (double), typeof (ZoomBox), new PropertyMetadata(.1));

		public static readonly DependencyProperty ValueProperty =
			DependencyProperty.Register("Value", typeof (double), typeof (ZoomBox), new PropertyMetadata(1.0, OnValueChanged));

		public static readonly DependencyProperty ZoomChangeProperty =
			DependencyProperty.Register("ZoomChange", typeof (double), typeof (ZoomBox), new PropertyMetadata(.2));

		public ZoomBox()
		{
			DefaultStyleKey = typeof (ZoomBox);
		}

		public double MinValue
		{
			get { return (double) GetValue(MinValueProperty); }
			set { SetValue(MinValueProperty, value); }
		}

		public double MaxValue
		{
			get { return (double) GetValue(MaxValueProperty); }
			set { SetValue(MaxValueProperty, value); }
		}

		public double Value
		{
			get { return (double) GetValue(ValueProperty); }
			set { SetValue(ValueProperty, value); }
		}

		public double ZoomChange
		{
			get { return (double) GetValue(ZoomChangeProperty); }
			set { SetValue(ZoomChangeProperty, value); }
		}

		protected Slider ZoomSlider { get; set; }

		protected Button PlusButton { get; set; }

		protected Button MinusButton { get; set; }

		public static void OnValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
		{
			double value = Convert.ToDouble(args.NewValue);

			var thisControl = (ZoomBox) obj;

			if (thisControl.MinusButton == null || thisControl.PlusButton == null)
				return;

			if (value + thisControl.ZoomChange > thisControl.MaxValue)
			{
				thisControl.MinusButton.IsEnabled = true;
				thisControl.PlusButton.IsEnabled = false;
			}
			else if (value - thisControl.ZoomChange < thisControl.MinValue)
			{
				thisControl.PlusButton.IsEnabled = true;
				thisControl.MinusButton.IsEnabled = false;
			}
			else
			{
				thisControl.MinusButton.IsEnabled = true;
				thisControl.PlusButton.IsEnabled = true;
			}
		}

		public override void OnApplyTemplate()
		{
			MinusButton = GetTemplateChild("PART_MinusButton") as Button;
			if (MinusButton != null)
				MinusButton.Click += MinusButton_Click;

			PlusButton = GetTemplateChild("PART_PlusButton") as Button;
			if (PlusButton != null)
				PlusButton.Click += PlusButton_Click;

			base.OnApplyTemplate();
		}

		private void PlusButton_Click(object sender, RoutedEventArgs e)
		{
			Value += ZoomChange;
		}

		private void MinusButton_Click(object sender, RoutedEventArgs e)
		{
			Value -= ZoomChange;
		}
	}
}